package com.vmj.classfile.entity;

import com.vmj.classfile.entity.constantinfo.ConstantClassInfo;
import com.vmj.classfile.entity.constantinfo.ConstantNameAndTypeInfo;
import com.vmj.classfile.entity.constantinfo.ConstantUtf8Info;

import java.util.List;

/**
 * Created by yangshoujun on 2017/8/5 下午11:27.
 */
public class ConstantPool {

    private List<? extends ConstantInfo> constantInfos;

    public List<? extends ConstantInfo> getConstantInfos() {
        return constantInfos;
    }

    public void setConstantInfos(List<ConstantInfo> constantInfos) {
        this.constantInfos = constantInfos;
    }

    public String[] getNameAndType(int index) {
        ConstantInfo constantInfo = constantInfos.get(index);
        if( !(constantInfo instanceof ConstantNameAndTypeInfo) ) {
            throw new RuntimeException("constantInfo class not match,class is:" + constantInfo.getClass());
        }

        ConstantNameAndTypeInfo constantNameAndTypeInfo = (ConstantNameAndTypeInfo) constantInfo;
        ConstantUtf8Info utf8Info = (ConstantUtf8Info) constantInfos.get(constantNameAndTypeInfo.getNameIndex());
        String name = utf8Info.getStr();
        utf8Info = (ConstantUtf8Info) constantInfos.get(constantNameAndTypeInfo.getDescriptorIndex());
        String type = utf8Info.getStr();

        return new String[]{name, type};
    }

    public String getUtf8(int index) {
        ConstantUtf8Info utf8 = (ConstantUtf8Info) constantInfos.get(index);
        return utf8.getStr();
    }

    public String getClassName(int index) {
        ConstantClassInfo classInfo = (ConstantClassInfo) constantInfos.get(index);
        int nameIndex = classInfo.getNameIndex();
        ConstantUtf8Info utf8 = (ConstantUtf8Info) constantInfos.get(nameIndex);
        return utf8.getStr();
    }
}
